package com.sita.cfmoto.my.adapter;

import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sita.cfmoto.R;
import com.sita.cfmoto.rest.RestClient;
import com.sita.cfmoto.rest.model.Inform;
import com.sita.cfmoto.rest.model.RestResponse;
import com.sita.cfmoto.rest.model.request.ConfirmUsersRequest;
import com.sita.cfmoto.support.Constants;
import com.sita.cfmoto.support.GlobalContext;
import com.sita.cfmoto.utils.InteractUtils;
import com.sita.cfmoto.utils.LocalStorage;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import cn.trinea.android.common.util.ToastUtils;
import de.hdodenhof.circleimageview.CircleImageView;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by lijuan zhang on 2016/8/11.
 */
public class NoticeAdapter extends RecyclerView.Adapter<NoticeAdapter.ViewHolder> {
    private OnItemClickListener itemClickListener;
    private OnJoinRequestHandleListener joinRequestHandleListener;
    private List<Inform> data = new ArrayList<>();

    public NoticeAdapter() {
    }

    public void setOnItemClickListener(OnItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    public void setOnJoinRequestHandleListener(OnJoinRequestHandleListener joinRequestHandleListener) {
        this.joinRequestHandleListener = joinRequestHandleListener;
    }


    public void setData(List<Inform> data) {
        this.data.clear();
        this.data.addAll(data);
//        notifyItemRangeChanged(0, data.size());
        notifyDataSetChanged();
    }

    public void appendData(List<Inform> data) {
        int currCount = getItemCount();
        this.data.addAll(data);
        notifyItemRangeInserted(currCount, data.size());
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_notice, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        //数据绑定
        Inform inform = this.data.get(position);
        holder.nickName.setText(inform.nickName);
        Picasso.with(GlobalContext.getGlobalContext()).load(inform.avatar).centerCrop().placeholder(R.drawable.dynamic_default_icon).fit()
                .into(holder.avatar);
        holder.content.setText(inform.info);

        if (inform.info.equals("申请加入你的活动")) {
            holder.refuse.setVisibility(View.VISIBLE);
            holder.agree.setVisibility(View.VISIBLE);

            holder.refuse.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ConfirmUsersRequest request = new ConfirmUsersRequest();
                    request.campaignId = Long.valueOf(inform.entityId);
                    request.userId = Long.valueOf(inform.informFromId);
                    request.state = Constants.FLAG_ACTIVE_APPLICATION_REFUSE; // refuse
                    RestClient.getRestNormalService().confirmActiveApplication(request, new Callback<RestResponse>() {
                        @Override
                        public void success(RestResponse restResponse, Response response) {
                            Log.d("活动", "refuse");
//                            refreshData();
                            if (joinRequestHandleListener != null) {
                                joinRequestHandleListener.onJoinRequestHandle(v, position);
                            }
                        }

                        @Override
                        public void failure(RetrofitError error) {
                            Log.d("活动", "refuse error");
                            ToastUtils.show(GlobalContext.getGlobalContext(), GlobalContext.getGlobalContext().getString(R.string.active_application_confirm_error));
                        }
                    });
                }
            });

            holder.agree.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ConfirmUsersRequest request = new ConfirmUsersRequest();
                    request.campaignId = Long.valueOf(inform.entityId);
                    request.userId = Long.valueOf(inform.informFromId);
                    request.state = Constants.FLAG_ACTIVE_APPLICATION_AGREE; // refuse
                    RestClient.getRestNormalService().confirmActiveApplication(request, new Callback<RestResponse>() {
                        @Override
                        public void success(RestResponse restResponse, Response response) {
                            Log.d("活动", "agree");
//                            refreshData();
                            if (joinRequestHandleListener != null) {
                                joinRequestHandleListener.onJoinRequestHandle(v, position);
                            }
                        }

                        @Override
                        public void failure(RetrofitError error) {
                            Log.d("活动", "agree error");
                            ToastUtils.show(GlobalContext.getGlobalContext(), GlobalContext.getGlobalContext().getString(R.string.active_application_confirm_error));
                        }
                    });
                }
            });
        } else {
            holder.refuse.setVisibility(View.GONE);
            holder.agree.setVisibility(View.GONE);
        }

        holder.itemLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (itemClickListener != null)
                    itemClickListener.onItemClick(v, position);
            }
        });
    }

    @Override
    public int getItemCount() {
        //返回数据长度
        return data.size();
    }

    public Inform getItem(int position) {
        if (position < getItemCount()) {
            return data.get(position);
        } else {
            return null;
        }
    }

    private void refreshData() {
        Log.d("通知", "refresh");
        InteractUtils.fetchInform(10, 0, new InteractUtils.FetchInformListCallback() {
            @Override
            public void onInformListFetched(List<Inform> informList) {
                if (informList != null && !informList.isEmpty()) {
                    LocalStorage.setLastNotificationTimeStamp(informList.get(0).doTime);
                    setData(informList);
                }
            }
        });
    }

    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

    public interface OnJoinRequestHandleListener {
        void onJoinRequestHandle(View view, int position);
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public RelativeLayout itemLayout;
        public CircleImageView avatar;
        public TextView nickName;
        public TextView content;
        public Button agree;
        public Button refuse;

        public ViewHolder(View view) {
            super(view);
            itemLayout = (RelativeLayout) view.findViewById(R.id.item_layout);
            avatar = (CircleImageView) view.findViewById(R.id.avatar);
            nickName = (TextView) view.findViewById(R.id.nick_name_txt);
            content = (TextView) view.findViewById(R.id.content_txt);
            agree = (Button) view.findViewById(R.id.agree_btn);
            refuse = (Button) view.findViewById(R.id.refuse_btn);

        }
    }
}
